import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Tree, Input, Popconfirm, message, Spin } from 'antd';
import { PrimaryGhostC, DATA_ENTRY, IconC, InputC } from '../../../comps';
import myStyle from './index.less';
import uuid from 'es6-uuid';
import _ from 'lodash';
import config from './dictComps';
import { tree } from 'd3';

const { TreeNode } = Tree;
@Form.create()
class LeftMenuC extends PureComponent {
  state = {
    checkedKeys: [], // 选中项
    treeData: undefined, // 树形结构数据
    isEdit: false, // 是否在编辑，
    expandFlag: !(window.screen.width < 1920), // 是否展开模板管理
    selectItem: undefined, // 选中的模板
    listData: [], // 模板列表
  };

  componentDidMount() {
    const { treeData, moduleList } = this.props;
    this.setState({
      treeData,
    });
    this.props.expandFlag(this.state.expandFlag);
    this.setState({
      listData: _.cloneDeep(moduleList),
    });
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    if (JSON.stringify(nextProps.moduleList) != JSON.stringify(this.props.moduleList)) {
      this.setState({
        listData: _.cloneDeep(nextProps.moduleList),
      });
    }
    if (JSON.stringify(nextProps.treeData) != JSON.stringify(this.props.treeData)) {
      this.setState({
        treeData: _.cloneDeep(nextProps.treeData),
      });
    }
    if (nextProps.moduleId != this.props.moduleId || nextProps.timeStamp != this.props.timeStamp) {
      if (nextProps.moduleId) {
        // 重新定位模板设置 模板设置重新加载
        // console.log('重新定位模板设置 模板设置重新加载');
        const temp = nextProps.moduleList || [];
        const arr = temp?.filter((item) => item.value == nextProps.moduleId);
        const obj = arr?.length ? arr[0] : {};
        obj.checked = obj.checked != undefined ? false : undefined; // 设置为位选择状态
        this.onModuleClick(obj, 'flag');
      }
    }
    if (nextProps.isFloatLeft != this.props.isFloatLeft) {
      // 悬浮时默认收起
      if (nextProps.isFloatLeft) {
        this.setState({
          expandFlag: false,
        });
        this.props.expandFlag(false);
      }
    }
  }

  showTree = () => {
    const { treeData, selectItem } = this.state;
    const result = [];
    this.treeToListDepth(treeData, result);
    return (
      <Tree
        checkable={true}
        showIcon={false}
        defaultExpandAll={true}
        onCheck={this.onCheck}
        checkedKeys={this.state.checkedKeys}
        expandedKeys={result}
        disabled={selectItem?.isSystem == '1'}
      >
        {this.renderTreeNodes(treeData)}
      </Tree>
    );
  };

  // 树形变成普通结构
  treeToListDepth = (tree, result) => {
    tree.forEach((item) => {
      result.push(item.key); // 将该节点压进去
      // 若该节点有子节点，则优先执行子节点
      if (Array.isArray(item.children) && item.children.length) {
        this.treeToListDepth(item.children, result);
      }
    });
    return result;
  };

  onCheck = (checkedKeys) => {
    const { selectItem } = this.state;
    this.setState({
      checkedKeys,
    });
    if (this.props.moduleId && selectItem?.value == this.props.moduleId) {
      // 当this.props.moduleId 与用户选中的模板id一致，则模板设置 复选框变化时，需要向外面抛出 当前选中的元素集合
      // console.log('通知面板更新', checkedKeys);
      this.props.currentModuleListChange(checkedKeys);
    }
  };

  renderTreeNodes = (data) =>
    data.map((item) => {
      if (item.children) {
        return (
          <TreeNode title={item.title} key={item.key} dataRef={item}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode key={item.key} {...item} />;
    });

  // 展开/收起模板管理
  expandMenu = () => {
    const { expandFlag } = this.state;
    this.setState({
      expandFlag: !expandFlag,
    });
    this.props.expandFlag(!expandFlag);
  };

  // 点击了某个模板
  onModuleClick = (object, type) => {
    const { listData, isEdit } = this.state;
    if (isEdit && !type) return;
    const selectItem = object.checked ? undefined : _.cloneDeep(object);
    this.setState({
      selectItem,
      checkedKeys: selectItem ? selectItem.moduleList : [],
    });
    listData.map((item) => {
      if (item.value == object.value) {
        item.checked = !object.checked;
      } else {
        item.checked = false;
      }
    });
    this.setState({
      listData: [...listData],
    });
  };

  // 修改
  editModel = () => {
    const { listData, selectItem } = this.state;
    listData.map((item) => {
      if (selectItem.value == item.value) {
        // 标记选中项为可编辑状态
        item.isEdit = true;
      }
    });
    this.setState({
      isEdit: true,
      listData: [...listData],
    });
  };

  // 模板名称修改
  titleChange = (e, obj) => {
    const { listData } = this.state;
    listData.map((item) => {
      if (obj.value == item.value) {
        // 标记选中项为可编辑状态
        item.title = e.target.value;
      }
    });
    this.setState({
      listData: [...listData],
    });
  };

  // 删除模板
  onDelete = () => {
    const { selectItem } = this.state;
    this.props.dispatch({
      type: 'profitOverviewM/deleteById',
      payload: {
        type: this.props.type,
        id: selectItem.value,
      },
      callback: () => {
        message.success('模板删除成功!');
        this.props.onChangeModuleList(selectItem.value, '2'); // 通知父组件
        this.reset(); // 页面元素重置
      },
    });
  };

  // 页面元素重置 并通知父组件
  reset = () => {
    this.setState({
      checkedKeys: [], // 选中项
      isEdit: false, // 是否在编辑，
      expandFlag: true, // 是否展开模板管理
      selectItem: undefined, // 选中的模板
    });
  };

  // 取消编辑
  cancleEdit = () => {
    const { listData, selectItem } = this.state;
    listData.map((item) => {
      if (selectItem && selectItem.value == item.value) {
        // 还原被编辑的元素
        for (const key in selectItem) {
          item[key] = selectItem[key];
        }
        const obj = { ...item };
        this.setState(
          {
            checkedKeys: [], // 选中项
            isEdit: false, // 是否在编辑，
            expandFlag: true, // 是否展开模板管理
          },
          () => {
            // 非新增状态下，点击取消，根据当前选中的模板，重新获取模块信息，更新模板设置的选项
            // console.log('重新定位', obj);
            this.onModuleClick(obj, 'flag');
          },
        );
      } else {
        item.isEdit = false; // 全部重置false 不可编辑
      }
    });
    const arr = listData.filter((item) => item.createName);
    this.setState({
      listData: [...arr],
    });
    if (!selectItem) this.reset(); // 新增状态下 点击取消页面恢复到未选中状态
  };

  // saveModel 保存当前编辑/新增模板
  saveModel = () => {
    const { selectItem, checkedKeys, listData } = this.state;
    if (checkedKeys && !checkedKeys.length) {
      message.warning('模板设置必选');
      return;
    }
    const arr = listData.filter((item) => item.isEdit) || [];
    if (!selectItem?.value && !arr[0]?.title) {
      message.warning('模板名称必填');
      return;
    }
    const args = {
      id: arr[0]?.isAdd ? undefined : selectItem.value,
      title: arr[0]?.title ? arr[0]?.title : selectItem.title,
      moduleList: checkedKeys,
      modular: this.props.type == 'barra' ? 'barra' : undefined,
    };
    this.props.dispatch({
      type: 'profitOverviewM/saveModuleData',
      payload: {
        type: this.props.type,
        ...args,
      },
      callback: () => {
        message.success('模板保存成功!');
        this.reset(); // 页面元素重置
        this.props.onChangeModuleList(args.id, arr[0]?.isAdd ? '0' : '1'); // 通知父组件
      },
    });
  };

  // 新增一个模板
  addNew = () => {
    const { listData } = this.state;
    listData.unshift({
      value: uuid(16),
      isEdit: true, // 状态变更为编辑状态
      isAdd: true, // 新增标志位
      isSystem: '0', // 非系统内置
    });
    listData.map((item) => (item.checked = false));
    this.setState({
      selectItem: undefined,
      listData: [...listData],
      isEdit: true, // 状态变更为编辑状态
    });
  };

  // 判断是否可删除和编辑
  judageEdit = () => {
    const { selectItem } = this.state;
    let editFlag;
    if (selectItem) {
      const flag = localStorage.getItem('antd-pro-userId') == selectItem?.userId; // 是否创建人就是登录人
      // isSystem: 0否 1是；是否系统内置
      editFlag = !!(selectItem.isSystem == '0' && flag);
    } else {
      editFlag = true;
    }
    return editFlag;
  };

  render() {
    const { treeData, isEdit, expandFlag, listData = [], selectItem } = this.state;
    const { loading, isFloatLeft } = this.props;
    const editFlag = this.judageEdit();
    return (
      <div className={myStyle.leftMenu}>
        {expandFlag && (
          <div className={isFloatLeft ? `${myStyle.expandCls1} ${myStyle.expandCls}` : myStyle.expandCls}>
            <div className={myStyle.modelTop}>
              <div>模板管理</div>
              <div>
                {!isEdit && (
                  <>
                    <IconC type='newly' title={'新增'} isHover={false} onClick={this.addNew} />
                    {selectItem && editFlag && <IconC type='edit' title={'编辑'} isHover={false} onClick={this.editModel} />}
                    {selectItem && editFlag && (
                      <Popconfirm title={'确定删除？'} icon={<ExclamationCircleOutlined />} onConfirm={this.onDelete}>
                        <IconC title={'删除'} type='delete' isHover={false} />
                      </Popconfirm>
                    )}
                  </>
                )}
                {(editFlag && selectItem) || isEdit ? (
                  <>
                    <IconC type='save' title={'保存'} isHover={false} onClick={this.saveModel} />
                    <IconC type='cancle' title={'取消'} isHover={false} onClick={this.cancleEdit} />
                  </>
                ) : null}
                <IconC type={'packUp'} title={'收起'} isHover={false} onClick={this.expandMenu} />
              </div>
            </div>
            <div className={myStyle.modelList}>
              <Spin spinning={loading.effects['profitOverviewM/getModuleList'] == true}>
                {listData &&
                  listData.map((item, key) => {
                    if (item.isEdit) {
                      return <Input max={50} key={key} value={item.title} onChange={(e) => this.titleChange(e, item)} />;
                    } else {
                      return (
                        <div
                          onClick={() => {
                            this.onModuleClick(item);
                          }}
                          key={key}
                          className={item.checked ? myStyle.checkColor : myStyle.normalColor}
                        >
                          <span title={item.title}>{item.title}</span>
                          <span title={item.createName}>{item.createName}</span>
                        </div>
                      );
                    }
                  })}
                {listData && !listData.length ? <div>请点击加号进行模板新增</div> : null}
              </Spin>
            </div>
            <div className={myStyle.modelTop}>
              <div>模板设置</div>
            </div>
            <Spin spinning={loading.effects['profitOverviewM/queryTreeData'] == true}>
              <div style={{ height: this.props.type == 'main' ? 'calc(100vh - 386px)' : '502px', width: '100%', minHeight: '40px', overflowY: 'auto' }}>
                {treeData && this.showTree()}
              </div>
            </Spin>
          </div>
        )}
        {!expandFlag && (
          <div className={isFloatLeft ? myStyle.closedCls1 : myStyle.closedCls}>
            <div>模板管理</div>
            <IconC type={isFloatLeft ? 'packUp' : 'packUp'} title={'展开'} isHover={false} onClick={this.expandMenu} />
          </div>
        )}
      </div>
    );
  }
}
export default connect(({ profitOverviewM, loading }) => ({
  profitOverviewM,
  loading,
}))(LeftMenuC);
